from flask import Flask, Response, request
from PyCmpltrtok.common import md5, uuid
import redis
import time
import json

app = Flask(__name__)
rdb = redis.Redis('127.0.0.1', 6379, 0)
PWD = 'my_password_001'


@app.route("/api", methods=['POST'])
def do_infer():
    """
    https://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask
    """
    # 接收输入
    req_json = request.get_json(force=True)  # 请求json
    
    def get_generator():
        xinput = req_json['input']
        xusername = req_json['username']

        # 防止蹭模型
        xcheck = req_json['check']
        xmy_check = md5(xinput + PWD + xusername)
        if xcheck.lower() != xmy_check.lower():
            print('Checking not passed!')
            return

        print('input:', xinput)

        xoutput = xinput
        for i in range(20):
            n = i + 1
            xoutput += f'{n}.'
            # 返回输出
            res_dict = dict()
            res_dict['input'] = xinput
            res_dict['output'] = xoutput
            yield json.dumps(res_dict).encode('utf8') + b'\0'

        # 返回输出
        res_dict = dict()
        res_dict['input'] = xinput
        res_dict['output'] = xoutput
        yield json.dumps(res_dict).encode('utf8') + b'\0'
            
    generator = get_generator()
    return Response(generator)


if '__main__' == __name__:
    # https://www.cnblogs.com/chaojiyingxiong/p/14988069.html
    app.run('0.0.0.0', 7777)
